package com.aiti.lulian.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.page.PageResult;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.constant.MiniProgramVersionConstant;
import com.aiti.lulian.dto.EnterpriseDto;
import com.aiti.lulian.dto.EnterpriseSelectDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.entity.crad.CardChangeCardRole;
import com.aiti.lulian.entity.crad.EnterpriseZfInfo;
import com.aiti.lulian.entity.newCard.ShowEnterpriseTrial;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.service.*;
import com.aiti.lulian.service.newCard.ShowEnterpriseTrialService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/lulianEnterprise")
public class LuLianEnterpriseController extends WebController {
    @Autowired
    ILuLianEnterpriseService luLianEnterpriseService;
    @Autowired
    ILuLianProductService luLianProductService;
    @Autowired
    ISysAttachmentService sysAttachmentService;
    @Autowired
    IShowEnterpriseMediaService mediaService;

    @Autowired
    ILuLianEnterpriseUserService luLianEnterpriseUserService;
    @Autowired
    CloudShowManagerSubService cloudShowManagerSubService;

    @Autowired
    ILuLianEnterpriseExtensionService luLianEnterpriseExtensionService;
    @Autowired
    private ShowEnterpriseTrialService showEnterpriseTrialService;


//    /**
//     * 根据当前登录用户ID查询
//     *
//     * @param
//     * @return com.aiti.base.core.utils.message.Message
//     * @date 2024/6/5 0005 15:25
//     * @author diaozhende
//     */
//    @GetMapping("/queryByCurrentUser")
//    public Message queryByCurrentUser(String userId) {
//        if(StrUtil.isEmpty(userId))
//            userId = findUserId(); // 获取当前登录用户ID
//        LuLianEnterprise luLianEnterprise = luLianEnterpriseService.queryByCurrentUser(userId);
//        return Message.success(luLianEnterprise);
//    }

    /**
     * 根据当前登录用户ID查询
     *
     * @param
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/6/5 0005 15:25
     * @author diaozhende
     */
    @GetMapping("/queryByCurrentUser")
    public Message queryByCurrentUser(String userId) {
        if(StrUtil.isEmpty(userId))
            userId = findUserId(); // 获取当前登录用户ID
        LuLianEnterpriseHistory luLianEnterpriseHistory = luLianEnterpriseService.queryByCurrentUser(userId);
        return Message.success(luLianEnterpriseHistory);
    }

    /**
     * 通过统信查询企业名称
     * @param uscc
     * @return
     */
    @GetMapping("/findCompanyNameByUscc")
    public Message findUserId(@RequestParam(value = "uscc",required = false) String uscc) {
        if(StringUtils.isBlank(uscc)){
            return Message.success("");
        }
        LuLianEnterprise companyInfo = luLianEnterpriseService.getOne(new QueryWrapper<LuLianEnterprise>().eq("unicode", uscc));
        if(companyInfo == null || StringUtils.isBlank(companyInfo.getBaseName())){
            return Message.fail("没有找到该企业名称");
        }
        return Message.success(companyInfo.getBaseName());
    }

    /**
     * 按条件查询企业列表
     *
     * @param enterpriseSelectDto
     * @return Message
     * @date 2024/6/7 14:38
     * @author chenxianzhen
     */
    @GetMapping("/getAllEnterprise")
    public Message getAllEnterprise(EnterpriseSelectDto enterpriseSelectDto) {
        List<LuLianEnterprise> list=new ArrayList<>();
        //分页查询企业列表
        enterpriseSelectDto.setPageSize(1000);
        Page<LuLianEnterprise> pageResult = luLianEnterpriseService.queryPage(enterpriseSelectDto);
        List<LuLianEnterprise> lulianlist = pageResult.getRecords();
        //获取企业的产品列表
        for (int i = 0; i <lulianlist.size() ; i++) {
            String baseId = lulianlist.get(i).getBaseId();
            List<LuLianProduct> pList = luLianProductService.getProductByEnterpriseId(baseId);
            if(pList.size()>=5){
                if(list.size()<4){
                    //获取产品图片附件
                    for (int j = 0; j < pList.size(); j++) {
                        String pBaseId = pList.get(j).getBaseId();
                        List<SysAttachment> attachments = sysAttachmentService.getByRelId(pBaseId);
                        pList.get(j).setAttachments(attachments);
                    }
                    lulianlist.get(i).setProducts(pList);
                    list.add(lulianlist.get(i));
                }else{
                    break;
                }
            }
        }

            PageResult result = getPageResult(list, enterpriseSelectDto.getPageNum(), enterpriseSelectDto.getPageSize(), (int)pageResult.getTotal());
        //List<LuLianEnterprise> list = luLianEnterpriseService.getAllByParams(enterpriseSelectDto);
        return Message.success(result);
    }

    @GetMapping("/page")
    public Message page(EnterpriseSelectDto enterpriseSelectDto) {
        //分页查询企业列表
        Page<LuLianEnterprise> pageResult = luLianEnterpriseService.queryPage(enterpriseSelectDto);
        PageResult result = getPageResult(pageResult.getRecords(), enterpriseSelectDto.getPageNum(), enterpriseSelectDto.getPageSize(), (int)pageResult.getTotal());
        return Message.success(result);
    }

    /**
     * 根据企业Id 获取产品图片
     *
     * @param enterpriseId
     * @return Message
     * @date 2024/6/7 10:08
     * @author chenxianzhen
     */

    @GetMapping("/getProductImg/{enterpriseId}")
    public Message getProductImg(@PathVariable("enterpriseId") String enterpriseId) {
        List<LuLianProduct> list = luLianProductService.getProductByEnterpriseId(enterpriseId);
        return Message.success(list);
    }

    /**
     * 根据企业Id查询企业图片
     *
     * @param enterpriseId
     * @return Message
     * @date 2024/6/7 14:39
     * @author chenxianzhen
     */
    @GetMapping("/getPlantImg/{enterpriseId}")
    public Message getPlantImg(@PathVariable("enterpriseId") String enterpriseId) {
        List<LuLianEnterprisePlantImg> list = luLianEnterpriseService.getPlantImg(enterpriseId);
        return Message.success(list);
    }

    @PostMapping("/saveEnterpriseUser")
    public Message saveEnterpriseUser(@RequestBody LuLianEnterpriseUser luLianEnterpriseUser) {
        return luLianEnterpriseService.saveEnterpriseUser(luLianEnterpriseUser);

    }

    @PostMapping("/updateEnterpriseUser")
    public Message updateEnterpriseUser(@RequestBody LuLianEnterpriseUser luLianEnterpriseUser) {
        return luLianEnterpriseService.updateEnterpriseUser(luLianEnterpriseUser);

    }

    @GetMapping("/getEnterpriseByUserId")
    public Message getEnterpriseByUserId(@RequestParam("userId") String userId) {
        return Message.success(luLianEnterpriseService.getEnterpriseUser(userId));
    }

    @DeleteMapping("/delEnterpriseUserByUserId")
    public Message delEnterpriseUserByUserId(@RequestParam("userId") String userId, @RequestParam("enterpriseId") String enterpriseId) {
        return Message.success(luLianEnterpriseService.delEnterpriseUserByUserId(userId, enterpriseId));
    }

    /**
     * 查询企业Logo地址
     * @param enterpriseId
     * @return
     */
    @GetMapping("/logo/{enterpriseId}")
    public Message selectEnterpriseLogo(@PathVariable("enterpriseId") String enterpriseId){
        return Message.success(luLianEnterpriseService.selectEnterpriseLogo(enterpriseId));
    }

    @PostMapping("/selectEnterpriseInfoByIds")
    public Message selectEnterpriseInfoByIds(@RequestBody List<String> enterpriseIds){
        return luLianEnterpriseService.selectEnterpriseInfoByIds(enterpriseIds);
    }

    @PutMapping("/updateVersion")
    @Transactional(rollbackFor = Exception.class)
    public Message updateVersion(@RequestBody EnterpriseSelectDto enterpriseSelectDto) {
        LuLianEnterprise oldEnterpriseInfo = luLianEnterpriseService.getById(enterpriseSelectDto.getBaseId());

        LuLianEnterprise enterprise = new LuLianEnterprise();
        enterprise.setBaseId(enterpriseSelectDto.getBaseId());
        enterprise.setMiniProgramVersion(enterpriseSelectDto.getMiniProgramVersion());
        luLianEnterpriseService.updateById(enterprise);

        if (oldEnterpriseInfo != null) {
            //这里在切换版的时候，需要给对应的用户增加角色
            // 0e107ee19e114509b68d6bb384789931  高级版
            //49977357bfaf4fa5a1094dfdb74b442f  基础版
//            String roleId = enterpriseSelectDto.getMiniProgramVersion() == 2 ? "0e107ee19e114509b68d6bb384789931" : "49977357bfaf4fa5a1094dfdb74b442f";
//            String oldRoleId = oldEnterpriseInfo.getMiniProgramVersion() == 2 ? "0e107ee19e114509b68d6bb384789931" : "49977357bfaf4fa5a1094dfdb74b442f";
            String roleId = MiniProgramVersionConstant.GaoJiAndTuoKeVersionList.contains(enterpriseSelectDto.getMiniProgramVersion()) ? "0e107ee19e114509b68d6bb384789931" : "49977357bfaf4fa5a1094dfdb74b442f";
            String oldRoleId = MiniProgramVersionConstant.GaoJiAndTuoKeVersionList.contains(oldEnterpriseInfo.getMiniProgramVersion()) ? "0e107ee19e114509b68d6bb384789931" : "49977357bfaf4fa5a1094dfdb74b442f";
            List<LuLianEnterpriseUser> list = luLianEnterpriseUserService.list(new QueryWrapper<LuLianEnterpriseUser>().eq("enterprise_id", enterpriseSelectDto.getBaseId()));
            if(list != null && list.size()>0){
                List<CardChangeCardRole> userRoleList = list.stream().map(item -> {
                    CardChangeCardRole build = CardChangeCardRole.builder()
                            .userId(item.getUserId())
                            .newRoleId(roleId)
                            .oldRoleId(oldRoleId)
                            .build();
                    return build;
                }).collect(Collectors.toList());
                if(userRoleList != null && userRoleList.size() > 0){
                    Message message = cloudShowManagerSubService.updateEnterpriseRyRole(userRoleList);
                    if(message.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                        throw new RuntimeException("保存失败");
                    }
                }
            }
        }



        return Message.success();
    }

    @GetMapping("/version")
    public Message version(EnterpriseDto dto){
        if(StringUtils.isEmpty(dto.getUserId())){
            dto.setUserId(findUserId());
        }
        return Message.success(luLianEnterpriseService.enterpriseVersion(dto));
    }

    @GetMapping("/selectEnterpriseInfoByName")
    public Message selectEnterpriseInfoByName(@RequestParam String enterpriseName){
        List<LuLianEnterprise> luLianEnterprises = luLianEnterpriseService.selectEnterpriseInfoByName(enterpriseName);
        return Message.success(luLianEnterprises);
    }

    /**
     * 保存政府名片信息
     * @param info
     * @return
     */
    @PostMapping("/saveZfInfo")
    @Transactional(rollbackFor = Exception.class)
    public Message saveZfInfo(@RequestBody EnterpriseZfInfo info){
        String userId = findUserId();
        String baseId = info.getBaseId();
        if (StrUtil.isBlank(baseId)) {
            //表示本次操作为新增
            LuLianEnterprise enterprise = new LuLianEnterprise();
            BeanUtils.copyProperties(info, enterprise);
            enterprise.setLogo(info.getPic());
            enterprise.setStatus("1");
            enterprise.setSfZf("1");
            luLianEnterpriseService.save(enterprise);
            info.setBaseId(enterprise.getBaseId());
            LuLianEnterpriseExtension enterpriseExtension = LuLianEnterpriseExtension.builder()
                    .enterpriseId(enterprise.getBaseId())
                    .build();
            luLianEnterpriseExtensionService.save(enterpriseExtension);
        } else {
            //表示本次操作为更新
            String baseName = info.getBaseName();
            String vrUrl = info.getVrUrl();
            String vrGif = info.getVrGif();
            String pic = info.getPic();
            String hyMainPic = info.getHyMainPic();
            String baseIntroduction = info.getBaseIntroduction();
            String province = info.getProvince();
            String city = info.getCity();
            String county = info.getCounty();
            String address = info.getAddress();
            LambdaUpdateWrapper<LuLianEnterprise> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(LuLianEnterprise::getBaseId, baseId)
                    .set(StrUtil.isNotBlank(baseName), LuLianEnterprise::getBaseName, baseName)
                    .set(StrUtil.isNotBlank(vrUrl), LuLianEnterprise::getVrUrl, vrUrl)
                    .set(LuLianEnterprise::getVrGif, vrGif)
                    .set(LuLianEnterprise::getPic, pic)
                    .set(LuLianEnterprise::getLogo, pic)
                    .set(LuLianEnterprise::getHyMainPic, hyMainPic)
                    .set(StrUtil.isNotBlank(baseIntroduction), LuLianEnterprise::getBaseIntroduction, baseIntroduction)
                    .set(StrUtil.isNotBlank(province), LuLianEnterprise::getProvince, province)
                    .set(StrUtil.isNotBlank(city), LuLianEnterprise::getCity, city)
                    .set(StrUtil.isNotBlank(county), LuLianEnterprise::getCounty, county)
                    .set(StrUtil.isNotBlank(address), LuLianEnterprise::getAddress, address)
                    .set(LuLianEnterprise::getStatus, "1");
            luLianEnterpriseService.update(updateWrapper);
        }

        mediaService.remove(new QueryWrapper<ShowEnterpriseMedia>().eq("pk_id", info.getBaseId()));
        if(StringUtils.isNotBlank(info.getMediaPath())){
            ShowEnterpriseMedia showEnterpriseMedia = new ShowEnterpriseMedia();
            showEnterpriseMedia.setMediaPath(info.getMediaPath());
            showEnterpriseMedia.setMediaType("video");
            showEnterpriseMedia.setMediaName(info.getMediaPath());
            showEnterpriseMedia.setPkId(info.getBaseId());
            showEnterpriseMedia.setBaseCreateTime(DateUtil.date());
            showEnterpriseMedia.setBaseCreateBy(userId);
            showEnterpriseMedia.setBaseUpdateTime(DateUtil.date());
            showEnterpriseMedia.setBaseUpdateBy(userId);
            mediaService.save(showEnterpriseMedia);
        }

        List<LuLianEnterpriseUser> list = luLianEnterpriseUserService.list(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId).eq("enterprise_id", info.getBaseId()));
        if(list.isEmpty()){
            LuLianEnterpriseUser user = new LuLianEnterpriseUser();
            user.setBaseId(IdUtil.simpleUUID());
            user.setEnterpriseId(info.getBaseId());
            user.setUserId(userId);
            luLianEnterpriseUserService.save(user);
        }
        return Message.success();
    }

    @GetMapping("/selectZfInfoById")
    public Message selectZfInfoById(){
        String userId = findUserId();
        LuLianEnterpriseUser userId1 = luLianEnterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
        if(userId1 != null){
            String enterpriseId = userId1.getEnterpriseId();
            if(StringUtils.isNotBlank(enterpriseId)){
                LuLianEnterprise byId = luLianEnterpriseService.getById(enterpriseId);
                if(byId != null){
                    String baseId = byId.getBaseId();
                    String baseName = byId.getBaseName();
                    String vrGif = byId.getVrGif();
                    String vrUrl = byId.getVrUrl();

                    ShowEnterpriseMedia pkId = mediaService.getOne(new QueryWrapper<ShowEnterpriseMedia>().eq("pk_id", byId.getBaseId()));
                    EnterpriseZfInfo zfInfo = new EnterpriseZfInfo();
                    zfInfo.setBaseId(baseId);
                    zfInfo.setBaseName(baseName);
                    zfInfo.setVrGif(vrGif);
                    zfInfo.setVrUrl(vrUrl);
                    zfInfo.setPic(byId.getPic());
                    zfInfo.setHyMainPic(byId.getHyMainPic());
                    zfInfo.setBaseIntroduction(byId.getBaseIntroduction());
                    zfInfo.setProvince(byId.getProvince());
                    zfInfo.setCity(byId.getCity());
                    zfInfo.setCounty(byId.getCounty());
                    zfInfo.setAddress(byId.getAddress());
                    if(pkId != null){
                        zfInfo.setMediaPath(pkId.getMediaPath());
                    }
                    return Message.success(zfInfo);
                }
            }
        }
        return Message.success(new EnterpriseZfInfo());
    }

    @Autowired
    private ILulianEnterpriseHistoryService historyService;

    /**
     * 用来判断需不需要显示开通会员的弹窗
     * @return
     */
    @GetMapping("/showActivityDialog")
    public Message showActivityDialog(){
        String userId = findUserId();
        LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
        if(enterpriseUser == null){
            return Message.success(false);
        }
        LuLianEnterpriseHistory history = historyService.getById(enterpriseUser.getEnterpriseId());
        LuLianEnterprise enterprise = luLianEnterpriseService.getById(enterpriseUser.getEnterpriseId());
        if(history != null && enterprise == null){
            return Message.success(true);
        }else{
            return Message.success(false);
        }
    }

    @Autowired
    private ILulianEnterpriseHistoryService lulianEnterpriseHistoryService;

    @GetMapping("/queryEnterpriseIdByUserId")
    public Message  queryEnterpriseIdByUserId(){
        String userId = findUserId();
        LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
        if(enterpriseUser == null){
            return Message.success("");
        }
        String enterpriseId = enterpriseUser.getEnterpriseId();
        LuLianEnterpriseHistory enterprise = lulianEnterpriseHistoryService.getById(enterpriseId);
        if(enterprise != null){
            return Message.success(enterprise.getBaseId());
        }
        return Message.success("");
    }

    /**
     * 新版名片小程序后台
     */
    @ApiOperation("获取企业信息")
    @GetMapping("/getEnterpriseInfo")
    public Message getEnterpriseInfo(@RequestParam("enterpriseId") String enterpriseId) {
        return Message.success(luLianEnterpriseService.getEnterpriseInfoById(enterpriseId));
    }

    /**
     * 新版名片小程序后台
     */
    @ApiOperation("获取试用版企业信息")
    @GetMapping("/getEnterpriseTrialInfo")
    public Message getEnterpriseTrialInfo(@RequestParam("enterpriseId") String enterpriseId) {
        return Message.success(showEnterpriseTrialService.getEnterpriseTrialInfoById(enterpriseId));
    }

    /**
     * 新版名片小程序后台
     */
    @ApiOperation("修改企业信息")
    @PutMapping("/updateEnterpriseInfo")
    public Message updateEnterpriseInfo(@RequestBody EnterpriseDto dto) {
        LuLianEnterprise luLianEnterprise = new LuLianEnterprise();
        BeanUtils.copyProperties(dto, luLianEnterprise);
        luLianEnterprise.setBaseId(dto.getEnterpriseId());
        if (StrUtil.isNotEmpty(dto.getPic())) {
            luLianEnterprise.setLogo(dto.getPic());
        }
        luLianEnterpriseService.updateById(luLianEnterprise);
        return Message.success();
    }

    /**
     * 新版名片小程序后台
     */
    @ApiOperation("修改试用版企业信息")
    @PutMapping("/updateEnterpriseTrialInfo")
    public Message updateEnterpriseTrialInfo(@RequestBody EnterpriseDto dto) {
        ShowEnterpriseTrial showEnterpriseTrial = new ShowEnterpriseTrial();
        BeanUtils.copyProperties(dto, showEnterpriseTrial);
        showEnterpriseTrial.setBaseId(dto.getEnterpriseId());
        if (StrUtil.isNotEmpty(dto.getPic())) {
            showEnterpriseTrial.setLogo(dto.getPic());
        }
        showEnterpriseTrialService.updateById(showEnterpriseTrial);
        return Message.success();
    }

    /**
     * 查询企业的资质认定类型及其上传的认证图片
     */
    @GetMapping("/getQualificationRecognition")
    public Message getQualificationRecognition(@RequestParam("enterpriseId") String enterpriseId) {
        LuLianEnterprise enterprise = luLianEnterpriseService.getById(enterpriseId);
        if (enterprise == null) {
            return Message.fail("企业信息失效");
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("qualificationRecognitionType", enterprise.getQualificationRecognitionType());
        resultMap.put("qualificationRecognitionPic", enterprise.getQualificationRecognitionPic());
        return Message.success(resultMap);
    }
}
